home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / pluginy Firefox / 52811 / 52811.xpi / chrome / content / AES / aes.js next >
Encoding:
JavaScript  |  2005-12-16  |  21.3 KB  |  556 lines

  1. /* rijndael.js      Rijndael Reference Implementation
  2.  
  3.     This is a modified version of the software described below,
  4.     produced in September 2003 by John Walker for use in the
  5.     JavsScrypt browser-based encryption package.  The principal
  6.     changes are replacing the original getRandomBytes function with
  7.     one which calls our pseudorandom generator (which must
  8.     be instantiated and seeded before the first call on getRandomBytes),
  9.     and changing keySizeInBits to 256.  Some code not required by the
  10.     JavsScrypt application has been commented out.  Please see
  11.     http://www.fourmilab.ch/javascrypt/ for further information on
  12.     JavaScrypt.
  13.     
  14.     The following is the original copyright and application
  15.     information.
  16.  
  17.    Copyright (c) 2001 Fritz Schneider
  18.  
  19.  This software is provided as-is, without express or implied warranty.  
  20.  Permission to use, copy, modify, distribute or sell this software, with or
  21.  without fee, for any purpose and by any individual or organization, is hereby
  22.  granted, provided that the above copyright notice and this paragraph appear 
  23.  in all copies. Distribution as a part of an application or binary must
  24.  include the above copyright notice in the documentation and/or other materials
  25.  provided with the application or distribution.
  26.  
  27.    As the above disclaimer notes, you are free to use this code however you
  28.    want. However, I would request that you send me an email 
  29.    (fritz /at/ cs /dot/ ucsd /dot/ edu) to say hi if you find this code useful
  30.    or instructional. Seeing that people are using the code acts as 
  31.    encouragement for me to continue development. If you *really* want to thank
  32.    me you can buy the book I wrote with Thomas Powell, _JavaScript:
  33.    _The_Complete_Reference_ :)
  34.  
  35.    This code is an UNOPTIMIZED REFERENCE implementation of Rijndael. 
  36.    If there is sufficient interest I can write an optimized (word-based, 
  37.    table-driven) version, although you might want to consider using a 
  38.    compiled language if speed is critical to your application. As it stands,
  39.    one run of the monte carlo test (10,000 encryptions) can take up to 
  40.    several minutes, depending upon your processor. You shouldn't expect more
  41.    than a few kilobytes per second in throughput.
  42.  
  43.    Also note that there is very little error checking in these functions. 
  44.    Doing proper error checking is always a good idea, but the ideal 
  45.    implementation (using the instanceof operator and exceptions) requires
  46.    IE5+/NS6+, and I've chosen to implement this code so that it is compatible
  47.    with IE4/NS4. 
  48.  
  49.    And finally, because JavaScript doesn't have an explicit byte/char data 
  50.    type (although JavaScript 2.0 most likely will), when I refer to "byte" 
  51.    in this code I generally mean "32 bit integer with value in the interval 
  52.    [0,255]" which I treat as a byte.
  53.  
  54.    See http://www-cse.ucsd.edu/~fritz/rijndael.html for more documentation
  55.    of the (very simple) API provided by this code.
  56.  
  57.                                                Fritz Schneider
  58.                                                fritz at cs.ucsd.edu
  59.  
  60. */
  61.  
  62.  
  63. // Rijndael parameters --  Valid values are 128, 192, or 256
  64.  
  65. var keySizeInBits = 256;
  66. var blockSizeInBits = 128;
  67.  
  68. //
  69. // Note: in the following code the two dimensional arrays are indexed as
  70. //       you would probably expect, as array[row][column]. The state arrays
  71. //       are 2d arrays of the form state[4][Nb].
  72.  
  73.  
  74. // The number of rounds for the cipher, indexed by [Nk][Nb]
  75. var roundsArray = [ ,,,,[,,,,10,, 12,, 14],, 
  76.                         [,,,,12,, 12,, 14],, 
  77.                         [,,,,14,, 14,, 14] ];
  78.  
  79. // The number of bytes to shift by in shiftRow, indexed by [Nb][row]
  80. var shiftOffsets = [ ,,,,[,1, 2, 3],,[,1, 2, 3],,[,1, 3, 4] ];
  81.  
  82. // The round constants used in subkey expansion
  83. var Rcon = [ 
  84. 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 
  85. 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 
  86. 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 
  87. 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 
  88. 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 ];
  89.  
  90. // Precomputed lookup table for the SBox
  91. var SBox = [
  92.  99, 124, 119, 123, 242, 107, 111, 197,  48,   1, 103,  43, 254, 215, 171, 
  93. 118, 202, 130, 201, 125, 250,  89,  71, 240, 173, 212, 162, 175, 156, 164, 
  94. 114, 192, 183, 253, 147,  38,  54,  63, 247, 204,  52, 165, 229, 241, 113, 
  95. 216,  49,  21,   4, 199,  35, 195,  24, 150,   5, 154,   7,  18, 128, 226, 
  96. 235,  39, 178, 117,   9, 131,  44,  26,  27, 110,  90, 160,  82,  59, 214, 
  97. 179,  41, 227,  47, 132,  83, 209,   0, 237,  32, 252, 177,  91, 106, 203, 
  98. 190,  57,  74,  76,  88, 207, 208, 239, 170, 251,  67,  77,  51, 133,  69, 
  99. 249,   2, 127,  80,  60, 159, 168,  81, 163,  64, 143, 146, 157,  56, 245, 
  100. 188, 182, 218,  33,  16, 255, 243, 210, 205,  12,  19, 236,  95, 151,  68,  
  101. 23,  196, 167, 126,  61, 100,  93,  25, 115,  96, 129,  79, 220,  34,  42, 
  102. 144, 136,  70, 238, 184,  20, 222,  94,  11, 219, 224,  50,  58,  10,  73,
  103.   6,  36,  92, 194, 211, 172,  98, 145, 149, 228, 121, 231, 200,  55, 109, 
  104. 141, 213,  78, 169, 108,  86, 244, 234, 101, 122, 174,   8, 186, 120,  37,  
  105.  46,  28, 166, 180, 198, 232, 221, 116,  31,  75, 189, 139, 138, 112,  62, 
  106. 181, 102,  72,   3, 246,  14,  97,  53,  87, 185, 134, 193,  29, 158, 225,
  107. 248, 152,  17, 105, 217, 142, 148, 155,  30, 135, 233, 206,  85,  40, 223,
  108. 140, 161, 137,  13, 191, 230,  66, 104,  65, 153,  45,  15, 176,  84, 187,  
  109.  22 ];
  110.  
  111. // Precomputed lookup table for the inverse SBox
  112. var SBoxInverse = [
  113.  82,   9, 106, 213,  48,  54, 165,  56, 191,  64, 163, 158, 129, 243, 215, 
  114. 251, 124, 227,  57, 130, 155,  47, 255, 135,  52, 142,  67,  68, 196, 222, 
  115. 233, 203,  84, 123, 148,  50, 166, 194,  35,  61, 238,  76, 149,  11,  66, 
  116. 250, 195,  78,   8,  46, 161, 102,  40, 217,  36, 178, 118,  91, 162,  73, 
  117. 109, 139, 209,  37, 114, 248, 246, 100, 134, 104, 152,  22, 212, 164,  92, 
  118. 204,  93, 101, 182, 146, 108, 112,  72,  80, 253, 237, 185, 218,  94,  21,  
  119.  70,  87, 167, 141, 157, 132, 144, 216, 171,   0, 140, 188, 211,  10, 247, 
  120. 228,  88,   5, 184, 179,  69,   6, 208,  44,  30, 143, 202,  63,  15,   2, 
  121. 193, 175, 189,   3,   1,  19, 138, 107,  58, 145,  17,  65,  79, 103, 220, 
  122. 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116,  34, 231, 173,
  123.  53, 133, 226, 249,  55, 232,  28, 117, 223, 110,  71, 241,  26, 113,  29, 
  124.  41, 197, 137, 111, 183,  98,  14, 170,  24, 190,  27, 252,  86,  62,  75, 
  125. 198, 210, 121,  32, 154, 219, 192, 254, 120, 205,  90, 244,  31, 221, 168,
  126.  51, 136,   7, 199,  49, 177,  18,  16,  89,  39, 128, 236,  95,  96,  81,
  127. 127, 169,  25, 181,  74,  13,  45, 229, 122, 159, 147, 201, 156, 239, 160,
  128. 224,  59,  77, 174,  42, 245, 176, 200, 235, 187,  60, 131,  83, 153,  97, 
  129.  23,  43,   4, 126, 186, 119, 214,  38, 225, 105,  20,  99,  85,  33,  12,
  130. 125 ];
  131.  
  132. // This method circularly shifts the array left by the number of elements
  133. // given in its parameter. It returns the resulting array and is used for 
  134. // the ShiftRow step. Note that shift() and push() could be used for a more 
  135. // elegant solution, but they require IE5.5+, so I chose to do it manually. 
  136.  
  137. function cyclicShiftLeft(theArray, positions) {
  138.   var temp = theArray.slice(0, positions);
  139.   theArray = theArray.slice(positions).concat(temp);
  140.   return theArray;
  141. }
  142.  
  143. // Cipher parameters ... do not change these
  144. var Nk = keySizeInBits / 32;                   
  145. var Nb = blockSizeInBits / 32;
  146. var Nr = roundsArray[Nk][Nb];
  147.  
  148. // Multiplies the element "poly" of GF(2^8) by x. See the Rijndael spec.
  149.  
  150. function xtime(poly) {
  151.   poly <<= 1;
  152.   return ((poly & 0x100) ? (poly ^ 0x11B) : (poly));
  153. }
  154.  
  155. // Multiplies the two elements of GF(2^8) together and returns the result.
  156. // See the Rijndael spec, but should be straightforward: for each power of
  157. // the indeterminant that has a 1 coefficient in x, add y times that power
  158. // to the result. x and y should be bytes representing elements of GF(2^8)
  159.  
  160. function mult_GF256(x, y) {
  161.   var bit, result = 0;
  162.   
  163.   for (bit = 1; bit < 256; bit *= 2, y = xtime(y)) {
  164.     if (x & bit) 
  165.       result ^= y;
  166.   }
  167.   return result;
  168. }
  169.  
  170. // Performs the substitution step of the cipher.  State is the 2d array of
  171. // state information (see spec) and direction is string indicating whether
  172. // we are performing the forward substitution ("encrypt") or inverse 
  173. // substitution (anything else)
  174.  
  175. function byteSub(state, direction) {
  176.   var S;
  177.   if (direction == "encrypt")           // Point S to the SBox we're using
  178.     S = SBox;
  179.   else
  180.     S = SBoxInverse;
  181.   for (var i = 0; i < 4; i++)           // Substitute for every byte in state
  182.     for (var j = 0; j < Nb; j++)
  183.        state[i][j] = S[state[i][j]];
  184. }
  185.  
  186. // Performs the row shifting step of the cipher.
  187.  
  188. function shiftRow(state, direction) {
  189.   for (var i=1; i<4; i++)               // Row 0 never shifts
  190.     if (direction == "encrypt")
  191.        state[i] = cyclicShiftLeft(state[i], shiftOffsets[Nb][i]);
  192.     else
  193.        state[i] = cyclicShiftLeft(state[i], Nb - shiftOffsets[Nb][i]);
  194.  
  195. }
  196.  
  197. // Performs the column mixing step of the cipher. Most of these steps can
  198. // be combined into table lookups on 32bit values (at least for encryption)
  199. // to greatly increase the speed. 
  200.  
  201. function mixColumn(state, direction) {
  202.   var b = [];                            // Result of matrix multiplications
  203.   for (var j = 0; j < Nb; j++) {         // Go through each column...
  204.     for (var i = 0; i < 4; i++) {        // and for each row in the column...
  205.       if (direction == "encrypt")
  206.         b[i] = mult_GF256(state[i][j], 2) ^          // perform mixing
  207.                mult_GF256(state[(i+1)%4][j], 3) ^ 
  208.                state[(i+2)%4][j] ^ 
  209.                state[(i+3)%4][j];
  210.       else 
  211.         b[i] = mult_GF256(state[i][j], 0xE) ^ 
  212.                mult_GF256(state[(i+1)%4][j], 0xB) ^
  213.                mult_GF256(state[(i+2)%4][j], 0xD) ^
  214.                mult_GF256(state[(i+3)%4][j], 9);
  215.     }
  216.     for (var i = 0; i < 4; i++)          // Place result back into column
  217.       state[i][j] = b[i];
  218.   }
  219. }
  220.  
  221. // Adds the current round key to the state information. Straightforward.
  222.  
  223. function addRoundKey(state, roundKey) {
  224.   for (var j = 0; j < Nb; j++) {                 // Step through columns...
  225.     state[0][j] ^= (roundKey[j] & 0xFF);         // and XOR
  226.     state[1][j] ^= ((roundKey[j]>>8) & 0xFF);
  227.     state[2][j] ^= ((roundKey[j]>>16) & 0xFF);
  228.     state[3][j] ^= ((roundKey[j]>>24) & 0xFF);
  229.   }
  230. }
  231.  
  232. // This function creates the expanded key from the input (128/192/256-bit)
  233. // key. The parameter key is an array of bytes holding the value of the key.
  234. // The returned value is an array whose elements are the 32-bit words that 
  235. // make up the expanded key.
  236.  
  237. function keyExpansion(key) {
  238.   var expandedKey = new Array();
  239.   var temp;
  240.  
  241.   // in case the key size or parameters were changed...
  242.   Nk = keySizeInBits / 32;                   
  243.   Nb = blockSizeInBits / 32;
  244.   Nr = roundsArray[Nk][Nb];
  245.  
  246.   for (var j=0; j < Nk; j++)     // Fill in input key first
  247.     expandedKey[j] = 
  248.       (key[4*j]) | (key[4*j+1]<<8) | (key[4*j+2]<<16) | (key[4*j+3]<<24);
  249.  
  250.   // Now walk down the rest of the array filling in expanded key bytes as
  251.   // per Rijndael's spec
  252.   for (j = Nk; j < Nb * (Nr + 1); j++) {    // For each word of expanded key
  253.     temp = expandedKey[j - 1];
  254.     if (j % Nk == 0) 
  255.       temp = ( (SBox[(temp>>8) & 0xFF]) |
  256.                (SBox[(temp>>16) & 0xFF]<<8) |
  257.                (SBox[(temp>>24) & 0xFF]<<16) |
  258.                (SBox[temp & 0xFF]<<24) ) ^ Rcon[Math.floor(j / Nk) - 1];
  259.     else if (Nk > 6 && j % Nk == 4)
  260.       temp = (SBox[(temp>>24) & 0xFF]<<24) |
  261.              (SBox[(temp>>16) & 0xFF]<<16) |
  262.              (SBox[(temp>>8) & 0xFF]<<8) |
  263.              (SBox[temp & 0xFF]);
  264.     expandedKey[j] = expandedKey[j-Nk] ^ temp;
  265.   }
  266.   return expandedKey;
  267. }
  268.  
  269. // Rijndael's round functions... 
  270.  
  271. function Round(state, roundKey) {
  272.   byteSub(state, "encrypt");
  273.   shiftRow(state, "encrypt");
  274.   mixColumn(state, "encrypt");
  275.   addRoundKey(state, roundKey);
  276. }
  277.  
  278. function InverseRound(state, roundKey) {
  279.   addRoundKey(state, roundKey);
  280.   mixColumn(state, "decrypt");
  281.   shiftRow(state, "decrypt");
  282.   byteSub(state, "decrypt");
  283. }
  284.  
  285. function FinalRound(state, roundKey) {
  286.   byteSub(state, "encrypt");
  287.   shiftRow(state, "encrypt");
  288.   addRoundKey(state, roundKey);
  289. }
  290.  
  291. function InverseFinalRound(state, roundKey){
  292.   addRoundKey(state, roundKey);
  293.   shiftRow(state, "decrypt");
  294.   byteSub(state, "decrypt");  
  295. }
  296.  
  297. // encrypt is the basic encryption function. It takes parameters
  298. // block, an array of bytes representing a plaintext block, and expandedKey,
  299. // an array of words representing the expanded key previously returned by
  300. // keyExpansion(). The ciphertext block is returned as an array of bytes.
  301.  
  302. function encrypt(block, expandedKey) {
  303.   var i;  
  304.   if (!block || block.length*8 != blockSizeInBits)
  305.      return; 
  306.   if (!expandedKey)
  307.      return;
  308.  
  309.   block = packBytes(block);
  310.   addRoundKey(block, expandedKey);
  311.   for (i=1; i<Nr; i++) 
  312.     Round(block, expandedKey.slice(Nb*i, Nb*(i+1)));
  313.   FinalRound(block, expandedKey.slice(Nb*Nr)); 
  314.   return unpackBytes(block);
  315. }
  316.  
  317. // decrypt is the basic decryption function. It takes parameters
  318. // block, an array of bytes representing a ciphertext block, and expandedKey,
  319. // an array of words representing the expanded key previously returned by
  320. // keyExpansion(). The decrypted block is returned as an array of bytes.
  321.  
  322. function decrypt(block, expandedKey) {
  323.   var i;
  324.   if (!block || block.length*8 != blockSizeInBits)
  325.      return;
  326.   if (!expandedKey)
  327.      return;
  328.  
  329.   block = packBytes(block);
  330.   InverseFinalRound(block, expandedKey.slice(Nb*Nr)); 
  331.   for (i = Nr - 1; i>0; i--) 
  332.     InverseRound(block, expandedKey.slice(Nb*i, Nb*(i+1)));
  333.   addRoundKey(block, expandedKey);
  334.   return unpackBytes(block);
  335. }
  336.  
  337. /* !NEEDED
  338. // This method takes a byte array (byteArray) and converts it to a string by
  339. // applying String.fromCharCode() to each value and concatenating the result.
  340. // The resulting string is returned. Note that this function SKIPS zero bytes
  341. // under the assumption that they are padding added in formatPlaintext().
  342. // Obviously, do not invoke this method on raw data that can contain zero
  343. // bytes. It is really only appropriate for printable ASCII/Latin-1 
  344. // values. Roll your own function for more robust functionality :)
  345.  
  346. function byteArrayToString(byteArray) {
  347.   var result = "";
  348.   for(var i=0; i<byteArray.length; i++)
  349.     if (byteArray[i] != 0) 
  350.       result += String.fromCharCode(byteArray[i]);
  351.   return result;
  352. }
  353. */
  354.  
  355. // This function takes an array of bytes (byteArray) and converts them
  356. // to a hexadecimal string. Array element 0 is found at the beginning of 
  357. // the resulting string, high nibble first. Consecutive elements follow
  358. // similarly, for example [16, 255] --> "10ff". The function returns a 
  359. // string.
  360.  
  361. function byteArrayToHex(byteArray) {
  362.   var result = "";
  363.   if (!byteArray)
  364.     return;
  365.   for (var i=0; i<byteArray.length; i++)
  366.     result += ((byteArray[i]<16) ? "0" : "") + byteArray[i].toString(16);
  367.  
  368.   return result;
  369. }
  370.  
  371. // This function converts a string containing hexadecimal digits to an 
  372. // array of bytes. The resulting byte array is filled in the order the
  373. // values occur in the string, for example "10FF" --> [16, 255]. This
  374. // function returns an array. 
  375.  
  376. function hexToByteArray(hexString) {
  377.   var byteArray = [];
  378.   if (hexString.length % 2)             // must have even length
  379.     return;
  380.   if (hexString.indexOf("0x") == 0 || hexString.indexOf("0X") == 0)
  381.     hexString = hexString.substring(2);
  382.   for (var i = 0; i<hexString.length; i += 2) 
  383.     byteArray[Math.floor(i/2)] = parseInt(hexString.slice(i, i+2), 16);
  384.   return byteArray;
  385. }
  386.  
  387. // This function packs an array of bytes into the four row form defined by
  388. // Rijndael. It assumes the length of the array of bytes is divisible by
  389. // four. Bytes are filled in according to the Rijndael spec (starting with
  390. // column 0, row 0 to 3). This function returns a 2d array.
  391.  
  392. function packBytes(octets) {
  393.   var state = new Array();
  394.   if (!octets || octets.length % 4)
  395.     return;
  396.  
  397.   state[0] = new Array();  state[1] = new Array(); 
  398.   state[2] = new Array();  state[3] = new Array();
  399.   for (var j=0; j<octets.length; j+= 4) {
  400.      state[0][j/4] = octets[j];
  401.      state[1][j/4] = octets[j+1];
  402.      state[2][j/4] = octets[j+2];
  403.      state[3][j/4] = octets[j+3];
  404.   }
  405.   return state;  
  406. }
  407.  
  408. // This function unpacks an array of bytes from the four row format preferred
  409. // by Rijndael into a single 1d array of bytes. It assumes the input "packed"
  410. // is a packed array. Bytes are filled in according to the Rijndael spec. 
  411. // This function returns a 1d array of bytes.
  412.  
  413. function unpackBytes(packed) {
  414.   var result = new Array();
  415.   for (var j=0; j<packed[0].length; j++) {
  416.     result[result.length] = packed[0][j];
  417.     result[result.length] = packed[1][j];
  418.     result[result.length] = packed[2][j];
  419.     result[result.length] = packed[3][j];
  420.   }
  421.   return result;
  422. }
  423.  
  424. // This function takes a prospective plaintext (string or array of bytes)
  425. // and pads it with pseudorandom bytes if its length is not a multiple of the block 
  426. // size. If plaintext is a string, it is converted to an array of bytes
  427. // in the process. The type checking can be made much nicer using the 
  428. // instanceof operator, but this operator is not available until IE5.0 so I 
  429. // chose to use the heuristic below. 
  430.  
  431. function formatPlaintext(plaintext) {
  432.   var bpb = blockSizeInBits / 8;               // bytes per block
  433.   var i;
  434.  
  435.   // if primitive string or String instance
  436.   if ((!((typeof plaintext == "object") &&
  437.         ((typeof (plaintext[0])) == "number"))) &&
  438.       ((typeof plaintext == "string") || plaintext.indexOf)) {
  439.     plaintext = plaintext.split("");
  440.     // Unicode issues here (ignoring high byte)
  441.     for (i=0; i<plaintext.length; i++)
  442.       plaintext[i] = plaintext[i].charCodeAt(0) & 0xFF;
  443.   } 
  444.  
  445.   i = plaintext.length % bpb;
  446.   if (i > 0) {
  447.     plaintext = plaintext.concat(getRandomBytes(bpb - i));
  448.   }
  449.   
  450.   return plaintext;
  451. }
  452.  
  453. // Returns an array containing "howMany" random bytes.
  454.  
  455. function getRandomBytes(howMany) {
  456.     var i, bytes = new Array();
  457.     
  458.     for (i = 0; i < howMany; i++) {
  459.         bytes[i] = prng.nextInt(255);
  460.     }
  461.     return bytes;
  462. }
  463.  
  464. // rijndaelEncrypt(plaintext, key, mode)
  465. // Encrypts the plaintext using the given key and in the given mode. 
  466. // The parameter "plaintext" can either be a string or an array of bytes. 
  467. // The parameter "key" must be an array of key bytes. If you have a hex 
  468. // string representing the key, invoke hexToByteArray() on it to convert it 
  469. // to an array of bytes. The third parameter "mode" is a string indicating
  470. // the encryption mode to use, either "ECB" or "CBC". If the parameter is
  471. // omitted, ECB is assumed.
  472. // 
  473. // An array of bytes representing the cihpertext is returned. To convert 
  474. // this array to hex, invoke byteArrayToHex() on it.
  475.  
  476. function rijndaelEncrypt(plaintext, key, mode) {
  477.   var expandedKey, i, aBlock;
  478.   var bpb = blockSizeInBits / 8;          // bytes per block
  479.   var ct;                                 // ciphertext
  480.  
  481.   if (!plaintext || !key)
  482.     return;
  483.   if (key.length*8 != keySizeInBits)
  484.     return; 
  485.   if (mode == "CBC") {
  486.     ct = getRandomBytes(bpb);             // get IV
  487. //dump("IV", byteArrayToHex(ct));
  488.   } else {
  489.     mode = "ECB";
  490.     ct = new Array();
  491.   }
  492.  
  493.   // convert plaintext to byte array and pad with zeros if necessary. 
  494.   plaintext = formatPlaintext(plaintext);
  495.  
  496.   expandedKey = keyExpansion(key);
  497.   
  498.   for (var block = 0; block < plaintext.length / bpb; block++) {
  499.     aBlock = plaintext.slice(block * bpb, (block + 1) * bpb);
  500.     if (mode == "CBC") {
  501.       for (var i = 0; i < bpb; i++) {
  502.         aBlock[i] ^= ct[(block * bpb) + i];
  503.       }
  504.     }
  505.     ct = ct.concat(encrypt(aBlock, expandedKey));
  506.   }
  507.  
  508.   return ct;
  509. }
  510.  
  511. // rijndaelDecrypt(ciphertext, key, mode)
  512. // Decrypts the using the given key and mode. The parameter "ciphertext" 
  513. // must be an array of bytes. The parameter "key" must be an array of key 
  514. // bytes. If you have a hex string representing the ciphertext or key, 
  515. // invoke hexToByteArray() on it to convert it to an array of bytes. The
  516. // parameter "mode" is a string, either "CBC" or "ECB".
  517. // 
  518. // An array of bytes representing the plaintext is returned. To convert 
  519. // this array to a hex string, invoke byteArrayToHex() on it. To convert it 
  520. // to a string of characters, you can use byteArrayToString().
  521.  
  522. function rijndaelDecrypt(ciphertext, key, mode) {
  523.   var expandedKey;
  524.   var bpb = blockSizeInBits / 8;          // bytes per block
  525.   var pt = new Array();                   // plaintext array
  526.   var aBlock;                             // a decrypted block
  527.   var block;                              // current block number
  528.  
  529.   if (!ciphertext || !key || typeof ciphertext == "string")
  530.     return;
  531.   if (key.length*8 != keySizeInBits)
  532.     return; 
  533.   if (!mode) {
  534.     mode = "ECB";                         // assume ECB if mode omitted
  535.   }
  536.  
  537.   expandedKey = keyExpansion(key);
  538.  
  539.   // work backwards to accomodate CBC mode 
  540.   for (block=(ciphertext.length / bpb)-1; block>0; block--) {
  541.     aBlock = 
  542.      decrypt(ciphertext.slice(block*bpb,(block+1)*bpb), expandedKey);
  543.     if (mode == "CBC") 
  544.       for (var i=0; i<bpb; i++) 
  545.         pt[(block-1)*bpb + i] = aBlock[i] ^ ciphertext[(block-1)*bpb + i];
  546.     else 
  547.       pt = aBlock.concat(pt);
  548.   }
  549.  
  550.   // do last block if ECB (skips the IV in CBC)
  551.   if (mode == "ECB")
  552.     pt = decrypt(ciphertext.slice(0, bpb), expandedKey).concat(pt);
  553.  
  554.   return pt;
  555. }
  556.